<?php

namespace app\admin\controller;

use app\common\model\Article as ArticleModel;
use think\App;

class Article extends Base
{

    protected $article;

    public function __construct(App $app, ArticleModel $article)
    {
        parent::__construct($app);
        $this->article = $article;
    }

    public function index()
    {
        if ($this->request->isAjax()) {
            $title = input('get.title');
            $where = [];
            if ($title) $where[] = ['title', 'like', '%' . $title . '%'];
            $result = $this->article->where($where)->order('id', 'desc')->paginate(10);
            ajaxSuccess($result);
        }
        return $this->fetch();
    }

    public function save(\app\admin\validate\Article $article)
    {
        if (isAjax()) {
            $data = $this->request->post(['id', 'title', 'content', 'status']);
            if (!$article->check($data)) ajaxError($article->getError());
            if (isset($data['id']) && $data['id'] > 0) {
                $result = $this->article->update($data);
            } else {
                $result = $this->article->save($data);
            }
            if (!$result)
                ajaxError('保存失败');
            ajaxSuccess();
        }
    }

    public function delete()
    {
        if (isAjax()) {
            $id = input('post.id');
            $result = $this->article::destroy($id);
            if ($result) {
                ajaxSuccess();
            }
        }
        ajaxError();
    }


}

